#include "SessionEventHandler.h"
#include <ut_debug.h>
#include "SessionMgr.h"
#include "Proxy.h"

using namespace utility::log;

CSessionEventHandler::CSessionEventHandler( utility::network::session * s )
{
    m_pSession = s;
    m_pProxy = NULL;
}


CSessionEventHandler::~CSessionEventHandler(void)
{
    m_pSession = NULL;
    m_pProxy = NULL;
}

void CSessionEventHandler::on_established()
{
    if (m_pProxy)
        m_pProxy->OnCliConnected();
}

void CSessionEventHandler::on_disconnected()
{
    if (m_pProxy)
        m_pProxy->OnCliDisconnected();
    m_pSession = NULL;
    CSessionMgr::Instance()->RecycleEventHandler(this);
}

void CSessionEventHandler::on_error( int32 error_code, const char * error_message )
{
    LOG(CRITICAL) << "Network error, code number" << error_code << ", message:"<<error_message;
    if (m_pProxy)
        m_pProxy->OnCliError(error_code, error_message);
    m_pSession = NULL;
    CSessionMgr::Instance()->RecycleEventHandler(this);
}

void CSessionEventHandler::send( void * message, size_t message_length )
{
    if (m_pSession)
        m_pSession->send(message, message_length);
}

void CSessionEventHandler::on_receive( const char * message, uint32 message_length )
{
    if (m_pProxy)
        m_pProxy->OnCliReceive(message, message_length);
}

void CSessionEventHandler::SetProxy( CProxy * pProxy )
{
    m_pProxy = pProxy;
}

void CSessionEventHandler::Disconnect()
{
    if (m_pSession)
        m_pSession->disconnect();
}

uint32 CSessionEventHandler::GetIPAddr()
{
    if (m_pSession)
        return m_pSession->get_remote_ip();
    return 0;
}

uint16 CSessionEventHandler::GetPort()
{
    if (m_pSession)
        return m_pSession->get_remote_port();
    return 0;
}
